//
//  COUserManager.swift
//  CocoProject
//
//  Created by Ruthless on 2023/8/28.
//

import UIKit
import HandyJSON

class COUserManager: NSObject {
    /// 用户信息，设置为nil，表示删除用户信息
    static var userInfo: COUserInfo? {
        get {
            return Self.getUser()
        }
        set {
            if let newValue = newValue {
                saveUser(newValue)
            } else {
                removeUser()
            }
        }
    }
    
    // MARK: - 归档路径设置
    private static var savePath: String {
        return "COUserInfo"
    }

    /// 是否登录
    static func isLogin() -> Bool {
        guard COUserManager.getUser() != nil else {return false} // 文件不存在
        return true
    }
    
    /// 存档
    private static func saveUser(_ user: COUserInfo) {
        let dataJson = user.toJSONString()
        UserDefaults.standard.setValue(dataJson, forKeyPath: COUserManager.savePath)
        UserDefaults.standard.synchronize()
//        do {
//            let data = try NSKeyedArchiver.archivedData(withRootObject: user, requiringSecureCoding: true)
//            UserDefaults.standard.set(data, forKey: COUserManager.savePath)
//            UserDefaults.standard.synchronize()
//        } catch let err {
//            debugPrint("用户数据缓存失败\(err)")
//        }
    }
    
    /// 获取用户信息
    private static func getUser() -> COUserInfo? {
        guard let dataJson = UserDefaults.standard.object(forKey: COUserManager.savePath) as? String else {
            return nil
        }
        let user = JSONDeserializer<COUserInfo>.deserializeFrom(json: dataJson)
        return user
        
//        guard let data = UserDefaults.standard.object(forKey: COUserManager.savePath) as? Data else {
//            return nil
//        }
//        do {
//            let userInfo = try NSKeyedUnarchiver.unarchivedObject(ofClass: COUserInfo.self, from: data)
//            return userInfo
//        } catch let err {
//            debugPrint("用户数据解档案失败\(err)")
//            return nil
//        }
    }
    
    /// 删档
    static func removeUser() {
        UserDefaults.standard.set(nil, forKey: COUserManager.savePath)
        UserDefaults.standard.synchronize()
    }
    
    /// 退出登录
    static func logout(_ complete: (()->Void)? = nil) {
        CONetwork.sendRequest(provider: loginProvider, target: .logout) { _ in
            self.removeUser()
            complete?()
        } failedBlock: { _, _ in
            self.logout()
            complete?()
        }

    }
}
